package com.village.friend.fifter;

import org.apache.commons.lang.StringUtils;
import org.springframework.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Enumeration;

public class RequestWrapper extends HttpServletRequestWrapper {
    private final String body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        body = getBodyString(request);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }

    /**
     * 获取请求Body
     *
     * @param request
     * @return
     */
    public String getBodyString(ServletRequest request) {
        String bodyString = "";
        String contentType = request.getContentType();
        try {
            if (StringUtils.isNotBlank(contentType) && (contentType.contains("multipart/form-data") || contentType.contains("x-www-form-urlencoded"))) {
                Enumeration<String> pars = request.getParameterNames();
                while (pars.hasMoreElements()) {
                    String n = pars.nextElement();
                    bodyString += n + "=" + request.getParameter(n) + "&";
                }
                bodyString = bodyString.endsWith("&") ? bodyString.substring(0, bodyString.length() - 1) : bodyString;
            } else {
                byte[] byteArray = StreamUtils.copyToByteArray(request.getInputStream());
                bodyString = new String(byteArray, "UTF-8");
            }
        } catch (IOException e) {
            return bodyString;
        }
        return bodyString;
    }

}
